<template>
  <div><h1>商品信息</h1></div>
  <div style="left: 40px">
    <el-form
      :model="form"
      label-width="auto"
      :inline="true"
      style="max-width: 1200px; text-align: left"
    >
      <el-form-item :inline="true" label="商品编号">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item :inline="true" label="商品名称">
        <el-input v-model="form.name1" />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select v-model="form.region" style="width: 200px">
          <el-option label="Zone one" value="shanghai" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品品牌">
        <el-select v-model="form.region1" style="width: 200px">
          <el-option label="Zone one" value="shanghai" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" style="width: 200px">
          <el-option label="禁用" value="shanghai" />
          <el-option label="启用" value="shanghai" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-col :span="11">
          <el-date-picker
            v-model="form.date1"
            type="date"
            placeholder="开始日期"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">至</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="form.date2"
            type="date"
            placeholder="结束日期"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-col :span="11">
          <el-date-picker
            v-model="form.date3"
            type="date"
            placeholder="开始日期"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">至</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="form.date4"
            type="date"
            placeholder="结束日期"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <br />
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button>重置</el-button>
        <el-button type="primary" @click="openDialog">新增</el-button>
        <!-- 新增商品弹出框 -->
        <el-dialog v-model="dialogVisible" title="新增商品" width="50%">
          <el-form
            :model="productForm"
            :rules="rules"
            ref="productFormRef"
            label-width="120px"
          >
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="name" style="width: 310px">
              <el-input
                v-model="productForm.name"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <br />
            <!-- 商品分类 -->
            <el-form-item label="商品分类" prop="category" style="width: 310px">
              <el-select
                v-model="productForm.category"
                placeholder="请选择商品分类"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <br />
            <!-- 商品品牌 -->
            <el-form-item label="商品品牌" prop="brand" style="width: 310px">
              <el-select
                v-model="productForm.brand"
                placeholder="请选择商品品牌"
              >
                <el-option
                  v-for="item in brands"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <br />
            <!-- 商品单位 -->
            <el-form-item label="商品单位" prop="unit" style="width: 310px">
              <el-select
                v-model="productForm.unit"
                placeholder="请选择商品单位"
              >
                <el-option
                  v-for="item in units"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <br />
            <!-- 建议采购价 -->
            <el-form-item
              label="建议采购价"
              prop="purchasePrice"
              style="width: 310px"
            >
              <el-input
                v-model.number="productForm.purchasePrice"
                placeholder="请输入建议采购价（元）"
              ></el-input>
            </el-form-item>
            <br />
            <!-- 建议销售价 -->
            <el-form-item
              label="建议销售价"
              prop="salePrice"
              style="width: 310px"
            >
              <el-input
                v-model.number="productForm.salePrice"
                placeholder="请输入建议销售价（元）"
              ></el-input>
            </el-form-item>
            <br />
            <!-- 图片上传 -->
            <el-form-item label="图片" prop="image" style="width: 310px">
              <el-upload
                class="upload-demo"
                action="http://localhost:8080/admin/common/upload"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :show-file-list="false"
                accept="image/*"
              >
                <el-button icon="el-icon-plus" circle></el-button>
              </el-upload>
            </el-form-item>
          </el-form>
          <br />
          <!-- 弹窗底部按钮 -->
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeDialog">取 消</el-button>
              <el-button type="primary" @click="saveProduct">保 存</el-button>
            </span>
          </template>
        </el-dialog>
      </el-form-item>
    </el-form>
  </div>
  <div id="data">
    <Suspense>
      <el-table :data="commod.data" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="productXu" label="商品编号" width="180" />
        <el-table-column prop="photo" label="商品图片" width="180"
          ><template #default="scope">
            <img
              :src="scope.row.photo"
              style="width: 50px; height: auto"
            /> </template
        ></el-table-column>
        <el-table-column prop="name" label="商品名称" width="180" />
        <el-table-column prop="category" label="商品分类" width="180" />
        <el-table-column prop="brand" label="商品品牌" width="180" />
        <el-table-column prop="ton" label="商品单位" width="180" />
        <el-table-column
          prop="suggestedPurchasePrice"
          label="建议采购价(元)"
          width="180"
        />
        <el-table-column
          prop="suggestedSellingPrice"
          label="建议销售价(元)"
          width="180"
        />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="修改时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">{{ scope.row.status? "启用":"禁用" }}</template></el-table-column>
        <el-table-column prop="status" label="操作" width="180">
          <template #default="scope">
            <el-button  @click="Button(scope.row)">
              {{ scope.row.status? "禁用":"启用" }}</el-button>
            <el-button @click="handleEdit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="Address" />
      </el-table>
    </Suspense>
  </div>
  <div>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      size="small"
      background
      layout="prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { useCommoditydata } from "@/store/Request";
import { onMounted, ref, reactive } from "vue";
import Bag from "./Axios.js";
export default {
  //商品信息
  setup() {
    const commod = useCommoditydata();
    let isDisabled = ref(false);
    //新增
    let dialogVisible = ref(false);
    
    // 表单数据对象
    let productForm = reactive({
      name: "",
      category: "",
      brand: "",
      unit: "",
      purchasePrice: null,
      salePrice: null,
      image: "",
    });
    //商品分类
    let categories = [];
    // 商品品牌
    let brands = [];
    //商品单位
    let units = [];
    const form = reactive({
      name: "",
      name1: "",
      region: "",
      region1: "",
      status: "",
      date1: "",
      date2: "",
      date3: "",
      date4: "",
    });
    // 当前页码
    const currentPage = ref(1);
    // 每页显示数量
    const pageSize = ref(10);
    // 总数据条数
    const total = ref(commod.total);
    // 打开弹出框
    const openDialog = () => {
      dialogVisible.value = true;
    };
    // 关闭弹出框
    const closeDialog = () => {
      dialogVisible.value = false;
      // 清空表单数据
      Object.assign(productForm, {
        name: "",
        category: "",
        brand: "",
        unit: "",
        purchasePrice: null,
        salePrice: null,
        image: "",
      });
    };
    function onSubmit() {
      Bag.get(
        `http://localhost:8080/admin/query/product?prodctCodeOrName=${
          form.name
        }&Name=${form.name1}&productBrand=${form.region}&productCatergory=${
          form.region1
        }&status=${form.status}&createTimeStart=${Time(
          form.date1
        )}&createTimeEnd=${Time(form.date2)}&updateTimeStart=${Time(
          form.date3
        )}&updateTimeEnd=${Time(form.date4)}&pageNum=1&pageSize=5`
      ).then((a) => {
        console.log();
        commod.data = a.data.data.list;
      });
    }
    function saveProduct() {
      Bag.post("http://localhost:8080/admin/addProduct", {
        /**
         * 商品名称
         */
        name: productForm.name,
        /**
        /**
     * 商品图片
     */
        photo: productForm.image,
        /**
         * 商品品牌
         */
        brandId: productForm.brand,
        brand:
          (brands.find((e) => e.value === productForm.brand) || {}).label || "",
        /**
         * 商品单位
         */
        tonId: productForm.unit,
        ton:
          (units.find((e) => e.value === productForm.unit) || {}).label || "",
        /**
         * 商品分类
         */
        categoryId: productForm.category,
        category:
          (categories.find((e) => e.value === productForm.category) || {})
            .label || "",
        /**
         * 建议采购价
         */
        suggestedPurchasePrice: productForm.purchasePrice,
        /**
         * 建议销售价
         */
        suggestedSellingPrice: productForm.salePrice,
      }).then((e) => {
        Object.assign(productForm, {
          name: "",
          category: "",
          brand: "",
          unit: "",
          purchasePrice: null,
          salePrice: null,
          image: "",
        });
      });
    }
    function handleCurrentChange(newPage) {
      Bag.get(
        `http://localhost:8080/admin/getProduct?page=${newPage}&pageSize=10`
      ).then((a) => {
        console.log(a);
        commod.data = a.data.data.records;
      });
    }
    // 修改状态
    function Button(a) {
      if(a.status!==0){
      a.status=0
      Bag.post(`http://localhost:8080/admin/updateProductStatus`,{
          id:a.id,
          status:`${a.status}`,
      }).then((e)=>{
        console.log(e);
        a.updateTime=e.data.data
      })
    }else{
      a.status=1
      Bag.post(`http://localhost:8080/admin/updateProductStatus`,{
          id:a.id,
          status:`${a.status}`,
      }).then((e)=>{
        console.log(e);
        a.updateTime=e.data.data
      })
    }
    }
    function Time(a) {
      // 假设这是你的UL时间（Unix时间戳带毫秒）
      let ulTime = +new Date(a);
      if (ulTime) {
        // 示例时间戳
        // 创建一个新的Date对象
        let date = new Date(ulTime);
        // 格式化输出为本地时间字符串
        console.log(date.toLocaleString());
        // 如果你需要特定的格式，比如'YYYY-MM-DD HH:mm:ss'
        let year = date.getFullYear();
        let month = ("0" + (date.getMonth() + 1)).slice(-2);
        let day = ("0" + date.getDate()).slice(-2);
        let hours = ("0" + date.getHours()).slice(-2);
        let minutes = ("0" + date.getMinutes()).slice(-2);
        let seconds = ("0" + date.getSeconds()).slice(-2);
        let formattedDate = `${year} - ${month} - ${day} ${hours}:${minutes}:${seconds}`;
        console.log(formattedDate);
        return formattedDate;
      } else {
        return 0;
      }
    }
    // 图片相应数据
    function handleUploadSuccess(response, file, fileList) {
      // 假设服务器返回的数据格式为 { code: 200, message: 'success', data: { imageUrl: '...' } }
      if (response.code === 200) {
        // 成功上传后，你可以在这里处理返回的数据，比如更新表单字段
        productForm.image = response.data; // 假设你需要将图片地址保存到表单中
      } else {
        console.error("图片上传失败: " + response.message);
      }
    }

    
    // 调用渲染数据
    function Data() {
      if (commod.data) {
        console.log(commod.data);
        commod.data.forEach((e) => {
          categories.push({
            value: e.categoryId,
            label: e.category,
          });
        });
        commod.data.forEach((e) => {
          brands.push({
            value: e.brandId,
            label: e.brand,
          });
        });
        commod.data.forEach((e) => {
          units.push({
            value: e.tonId,
            label: e.ton,
          });
        });
        console.log(categories, brands, units);
      }
    }
    onMounted(() => {
      Data();
    });
    return {
      Data,
      commod,
      isDisabled,
      form,
      onSubmit,
      dialogVisible,
      productForm,
      openDialog,
      closeDialog,
      saveProduct,
      categories,
      brands,
      units,
      Button,
      handleUploadSuccess,
      currentPage,
      pageSize,
      total,
      handleCurrentChange,
      
    };
  },
};
</script>

<style scoped>
li {
  list-style-type: none;
}
#data {
  bottom: 10px;
}
.upload-demo {
  text-align: center;
}
</style>